package com.voxel.sense.infomsg.module.user.personal.portrait;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.ConvertUtils;
import com.example.com.common.utils.FileUtils;
import com.example.com.common.utils.IntentUtils;
import com.example.com.common.utils.L;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.utils.AppFileUtil;
import com.voxel.sense.infomsg.utils.FileProvider7;
import com.voxel.sense.infomsg.utils.GlideUtils;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.share.SPEngine;
import droidninja.filepicker.FilePickerBuilder;
import droidninja.filepicker.FilePickerConst;
import droidninja.filepicker.utils.Orientation;
import me.jessyan.progressmanager.ProgressListener;
import me.jessyan.progressmanager.body.ProgressInfo;

public class SetMyPortraitActivity extends BViewActivity<PortraitContract.Presenter>
        implements PortraitContract.View {

    @BindView(R.id.iv_pic)
    ImageView iv_pic;
    @BindView(R.id.tv_album)
    TextView tv_album;
    @BindView(R.id.tv_take_photo)
    TextView mTvTakePhoto;
    @BindView(R.id.titlebar)
    TextTitleBar titlebar;
    private File mHeadPicFile; //拍照后图片的文件


    public static void show(Context context) {
        context.startActivity(new Intent(context, SetMyPortraitActivity.class));
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_set_my_portrait;
    }

    @Override
    protected PortraitContract.Presenter initPresenter() {
        return new PortraitPresenter(this);
    }

    @Override
    protected void initData() {
        super.initData();
        titlebar.setTitleText("设置头像");
        String portrait = SPEngine.getSPEngine().getUserInfo().getPortrait();
        if (!TextUtils.isEmpty(portrait)) {
            GlideUtils.GlideLoadPortrait(this, portrait, iv_pic);
        }
    }


    @OnClick({R.id.tv_album, R.id.tv_take_photo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_album://从相册选取图片回调
                FilePickerBuilder.getInstance()
                        .setActivityTheme(R.style.FilePickerTheme)
                        .setMaxCount(1)
                        .enableVideoPicker(false)//是否显示视频
                        .enableCameraSupport(false)//是否能选择相机
                        .showGifs(false)//是否显示gif图
                        .showFolderView(false)//是否显示文件夹
                        .enableSelectAll(true)//是否选中全部，这个选中只有没有选中数量的情况下才能使用
                        .enableImagePicker(true)
                        .setCameraPlaceholder(R.mipmap.custom_camera)//相机图片
                        .withOrientation(Orientation.UNSPECIFIED)
                        .pickPhoto(this);//显示文件
                break;
            case R.id.tv_take_photo://调用相机照片
                //拍照后的图片路径
                mHeadPicFile = new File(AppFileUtil.getPhoneImageDir(), Constants.IMAGE_FILE_NAME);
                //图片存在的情况下，调用相机会直接显示存在的照片
                deletePick(mHeadPicFile.getAbsolutePath());
                //获取存储图片的uri
                Uri uriForFile = FileProvider7.getUriForFile(mHeadPicFile);
                //获取跳转拍照的意图
                Intent captureIntent = IntentUtils.getCaptureIntent(uriForFile);
                startActivityForResult(captureIntent, IntentConstants.REQUEST_CODE_TAKE_PHOTO);
                break;
        }
    }

    private void deletePick(String path) {
        if (!TextUtils.isEmpty(path)) {
            FileUtils.deleteDir(path);
            FileUtils.deleteFile(path);
            String url = MediaStore.Images.Media.DATA + "='" + path + "'";
            getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, url, null);
            AppFileUtil.updateMediaStore(path);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IntentConstants.REQUEST_CODE_TAKE_PHOTO && FileUtils.isFileExists(mHeadPicFile)) { //拍照成功回调
            /**
             * 这里不将拍照的图片更新到手机的相册中去。
             * 因为头像拍照每次存储的图片文字路径名称是一样的，若需要将头像更新到相册中，需要将原有的缩略图删除并更新。
             * 同时需要注意，app内部调起图片墙时，图片加载框架的缓存问题。可能会产生新拍的头像照片，没有显示而是显示旧的头像照片。
             * 如glide等框架就是用路径作为缓存key
             * 若要更新头像到相册中，较为简单的解决方案让每次拍照的存储的图片路径名不一样即可。
             *
             */
            mPresenter.doHandlerPhoto(mHeadPicFile);
//            AppFileUtil.notifyMediaStore(mHeadPicFile);
        } else if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {//裁剪图片回调
            final Uri resultUri = UCrop.getOutput(data);
            String path = ConvertUtils.uriToPath(Factory.app(), resultUri);
            resultUri.getAuthority();
            mPresenter.doUploadPortrait(new File(path));

        } else if (resultCode == UCrop.RESULT_ERROR) {//裁剪失败回调
            final Throwable cropError = UCrop.getError(data);

        } else if (requestCode == FilePickerConst.REQUEST_CODE_PHOTO &&
                resultCode == Activity.RESULT_OK && data != null) {//获取相册照片回调
            //清空集合，重新加载数据
            ArrayList<String> stringArrayListExtra = data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA);
            if (stringArrayListExtra != null && stringArrayListExtra.size() > 0) {
                String imgPath = stringArrayListExtra.get(0);
                mPresenter.doHandlerPhoto(new File(imgPath));
            }
        }
    }

    private ProgressListener getUploadListener() {
        return new ProgressListener() {
            @Override
            public void onProgress(ProgressInfo progressInfo) {
                L.d("--Upload-- " + progressInfo.getPercent() + " %  " + progressInfo.getSpeed() + " byte/s  " + progressInfo.toString());
                if (progressInfo.isFinish()) {
                    L.d("ProgressListener-isFinish");
                }
            }

            @Override
            public void onError(long id, Exception e) {
                L.d("onError-取消网络");
            }
        };
    }

    @Override
    public void onUploadSuccess(String portraitUrl) {
        GlideUtils.GlideLoadPortrait(this, portraitUrl, iv_pic);
    }

    @Override
    public void onShowClipPhoto(File file) {
        String ext = FileUtils.getFileExtension(file);   //获取文件名
        String imagePath = AppFileUtil.getImageDir() + File.separator + System.currentTimeMillis() + "." + ext;
        UCrop.of(Uri.fromFile(file), Uri.fromFile(new File(imagePath)))
                .withAspectRatio(1, 1)
                .start(this);
    }

}
